package juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类
 */
class Ticket{
    private int number = 30;
    Lock lock = new ReentrantLock();
    public void sale(){
        lock.lock();
        try {
            if (number>0){
                System.out.println(Thread.currentThread().getName()+":"+number--+"已卖出，还剩："+number);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}
public class SaleTicketDemo01 {

    public static void main(String[] args) {
        final Ticket ticket = new Ticket();
//        new Thread(new Runnable() {
//            public void run() {
//                for (int i = 0;i<=40;i++){
//                    ticket.sale();
//                }
//            }
//        },"A").start();
//        new Thread(new Runnable() {
//            public void run() {
//                for (int i = 0;i<=40;i++){
//                    ticket.sale();
//                }
//            }
//        },"B").start();
//        new Thread(new Runnable() {
//            public void run() {
//                for (int i = 0;i<=40;i++){
//                    ticket.sale();
//                }
//            }
//        },"C").start();

        new Thread(()->{for (int i = 0;i<=40;i++)ticket.sale();},"A").start();
        new Thread(()->{for (int i = 0;i<=40;i++)ticket.sale();},"B").start();
        new Thread(()->{for (int i = 0;i<=40;i++)ticket.sale();},"C").start();
    }
}
